/*
 * Copyright (C) 2010 Moduad Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.beem.push.utils;

import java.io.FileInputStream;










import java.io.IOException;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.util.EncodingUtils;

import com.spice.im.ContactFrameActivity;
import com.spice.im.OtherProfileActivity;
import com.spice.im.R;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.stb.core.test.msg.Base64;
//import com.stb.core.test.msg.R;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.service.XmppConnectionAdapter;
//import com.test.R;
//import com.stb.isharemessage.ui.ProgressWebView;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;
//import com.stb.isharemessage.utils.HeaderLayout.onRightImageButtonClickListener;
////import com.stb.isharepush.R;
//import com.test2.R;




import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

/** 
 * Activity for displaying the notification details view.
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class NotificationDetailsActivity extends Activity {
    private String callbackActivityPackageName = "com.test2";;

    private String callbackActivityClassName = "com.test2.MainActivity";;
    
	private HeaderLayout mHeaderLayout;// ������
//	private TextView textTitle;
	private ProgressWebView mWebView;
//	ProgressBar progressBar;
	private boolean isOnPause = false; 
//    private Button okButton;
	
	private String notificationId = "";
	private String notificationApiKey = "";
	private String notificationTitle = "";
	private String notificationMessage = "";
	private String notificationUri = "";
	
	private NotificationManager notificationManager;
	
    public NotificationDetailsActivity() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.newnotificationdetails_activity);
	    
	    this.notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
	    
//	    mHeaderLayout = (HeaderLayout) findViewById(R.id.otherprofile_header);

//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setTitleRightImageButton("������Ϣ", null,
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());

	    mHeaderLayout = (HeaderLayout) findViewById(R.id.otherprofile_header);
	    
//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
//		mHeaderLayout.setTitleRightImageButton("搜索结果", null,
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());
	    
        mWebView = (ProgressWebView)findViewById(R.id.notification_detail_webview);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setDefaultFontSize(14);
        /*
        Intent intent = getIntent();
        notificationId = intent
                .getStringExtra(Constants.NOTIFICATION_ID);
        notificationApiKey = intent
                .getStringExtra(Constants.NOTIFICATION_API_KEY);
        notificationTitle = intent
                .getStringExtra(Constants.NOTIFICATION_TITLE);
        notificationMessage = intent
                .getStringExtra(Constants.NOTIFICATION_MESSAGE);
        notificationUri = intent
                .getStringExtra(Constants.NOTIFICATION_URI);
        if(notificationId!=null){
        	try{
        		notificationManager.cancel(Integer.parseInt(notificationId));
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        }
        createView2(notificationTitle, notificationMessage,
              notificationUri);
        */
//        BeemApplication.getInstance().addActivity(this);
    }

    
    private void createView2(final String title, final String message,
            final String uri) {
//    	textTitle = (TextView)findViewById(R.id.notificationtitle);
//        textTitle.setText(title);
//        textTitle.setTextSize(18);
//        textTitle.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
//        textTitle.setTextColor(0xff000000);
//        textTitle.setGravity(Gravity.CENTER);
        
//    	progressBar = (ProgressBar)findViewById(R.id.xProgressBar);
    	/*
        mWebView = (ProgressWebView)findViewById(R.id.notification_detail_webview);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setDefaultFontSize(14);
        */
//        mWebView.setBackgroundColor(0);
//        mWebView.setBackgroundColor(Color.GREEN);  
        

        String temp = readFileSdcardFile(message);
        String data = temp;
        try{
            String base64Data = URLDecoder.decode(data,"UTF-8"); 
		    byte[] b = Base64.decode(base64Data, Base64.NO_WRAP);
		    data = new String(b,"UTF-8");
        }catch(Exception e){
        	e.printStackTrace();
        	data = temp;
        }
//        mWebView.loadData(data, mimeType, encoding)
        mWebView.loadData(data, "text/html;charset=UTF-8", null);
//        mWebView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, failUrl)
//        mWebView.loadDataWithBaseURL(XmppConnectionAdapter.downloadPrefix.substring(0, XmppConnectionAdapter.downloadPrefix.length()-1), data, "text/html;charset=UTF-8",null, null);
        

        
        
//        okButton = (Button) findViewById(R.id.collapse_restart);
//        okButton.setWidth(100);
//        
//        
//        okButton.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View view) {
//                Intent intent;
//                if (uri != null
//                        && uri.length() > 0
//                        && (uri.startsWith("http:") || uri.startsWith("https:")
//                                || uri.startsWith("tel:") || uri
//                                .startsWith("geo:"))) {
//                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
//                } else {
//                    intent = new Intent().setClassName(
//                            callbackActivityPackageName,
//                            callbackActivityClassName);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                    // intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
//                    // intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//                }
//
//                NotificationDetailsActivity.this.startActivity(intent);
//                NotificationDetailsActivity.this.finish();
//            }
//        });
    }
    

    
    /**
     * ��Activityִ��onPause()ʱ��WebViewִ��pause
     */ 
    @Override 
    protected void onPause() { 
        super.onPause(); 
        try { 
            if (mWebView != null) { 
                mWebView.getClass().getMethod("onPause").invoke(mWebView, (Object[]) null); 
                isOnPause = true; 
            } 
   
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 

    } 
    /**
     * ��Activityִ��onResume()ʱ��WebViewִ��resume
     */ 
    @Override 
    protected void onResume() { 
        super.onResume(); 
        try { 
            if (isOnPause) { 
                if (mWebView != null) { 
                    mWebView.getClass().getMethod("onResume").invoke(mWebView, (Object[]) null); 
                } 
                isOnPause = false; 
            } 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        Intent intent = getIntent();
        notificationId = intent
                .getStringExtra(Constants.NOTIFICATION_ID);
        notificationApiKey = intent
                .getStringExtra(Constants.NOTIFICATION_API_KEY);
        notificationTitle = intent
                .getStringExtra(Constants.NOTIFICATION_TITLE);
        

		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("招呼消息", notificationTitle,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
        
        notificationMessage = intent
                .getStringExtra(Constants.NOTIFICATION_MESSAGE);
        notificationUri = intent
                .getStringExtra(Constants.NOTIFICATION_URI);
        if(notificationId!=null){
        	try{
        		notificationManager.cancel(Integer.parseInt(notificationId));
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        }
        createView2(notificationTitle, notificationMessage,
              notificationUri);
    } 
       
    /**
     * �ô��Ĵ�����Ϊ��Ҫ:
     * Ӧ�����������ſؼ���ʧ�Ժ�,��ִ��mWebView.destroy()
     * ���򱨴�WindowLeaked
     */ 
    @Override 
    protected void onDestroy() { 
        super.onDestroy(); 
//        notificationManager.cancelAll();
        if (mWebView != null) { 
//            mWebView.getSettings().setBuiltInZoomControls(true); 
//            mWebView.setVisibility(View.GONE); 
//            long delayTime = ViewConfiguration.getZoomControlsTimeout(); 
//            new Timer().schedule(new TimerTask() { 
//                @Override 
//                public void run() { 
//                    mWebView.destroy(); 
//                    mWebView = null; 
//                } 
//            }, delayTime); 
        	mWebView.removeAllViews();
        	mWebView.destroy();
        	mWebView = null; 
   
        } 
        isOnPause = false; 
    } 
    
    //��SD�е��ļ�  
    public String readFileSdcardFile(String fileName){   
	    String res="";
	    FileInputStream fin = null;
	    int length = 0;
	    byte [] buffer = null;
	    try{   
	         fin = new FileInputStream(fileName); 
	         length = fin.available();   
	         buffer = new byte[length];   
	         fin.read(buffer);       
	         res = EncodingUtils.getString(buffer, "UTF-8");   
	         fin.close();       
	         fin = null;
	    }catch(IOException e){
	    	return null;
	    }catch(Exception e){   
	        e.printStackTrace();
	        return null;
	     }finally{
	    	if(fin!=null)
	    		try{
	    			fin.close();
	    			fin = null;
	    		}catch(Exception e){
	    		}
	      }  
	    return res;   
    } 
//	private class OnRightImageButtonClickListener implements
//	onRightImageButtonClickListener {
//	
//		@Override
//		public void onClick() {
//            Intent intent;
//            if (notificationUri != null
//                    && notificationUri.length() > 0
//                    && (notificationUri.startsWith("http:") || notificationUri.startsWith("https:")
//                            || notificationUri.startsWith("tel:") || notificationUri
//                            .startsWith("geo:"))) {
//                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(notificationUri));
//            } else {
//                intent = new Intent().setClassName(
//                        callbackActivityPackageName,
//                        callbackActivityClassName);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                // intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
//                // intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//            }
//
//            NotificationDetailsActivity.this.startActivity(intent);
//            NotificationDetailsActivity.this.finish();
//
//		}
//	}
    
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(NotificationDetailsActivity.this, ContactFrameActivity.class);
	    	intent.putExtra("refreshroster", "true");
			startActivity(intent);
			NotificationDetailsActivity.this.finish();
		}
	}
}
